package opencv.service.examples;


import java.awt.AWTException;
import java.awt.Image;
import java.awt.Rectangle;
import java.util.List;

import opencv.service.Application;
import opencv.service.SimpleDebugGUI;
import opencv.service.algorithms.FaceDetection;
import opencv.service.algorithms.FaceTracker;
import opencv.service.servers.TCPServer;

import com.googlecode.javacv.jna.cxcore.IplImage;

/**
 * @author Aakash Polra
 */
public class FaceDetectionGUIServer extends SimpleDebugGUI {
	
	private static final long serialVersionUID = 1L;
	private volatile boolean showDebug;

	private FaceTracker algorithm1;
	
	protected TCPServer tcpServer;
	
	public FaceDetectionGUIServer(int port) throws AWTException {
		super();
		tcpServer = new TCPServer(port);
	}
	
	@Override
	protected void initApplication() {
		application = new Application() {
			@Override
			public void onAfterAlgorithmsRan(IplImage lastFrame, IplImage currentFrame) {
				super.onAfterAlgorithmsRan(lastFrame, currentFrame);
			}
		};
		
		algorithm1 = new FaceTracker(FaceDetection.DEFAULT_OPENCV2_FACE_CASCADE, FaceDetection.DEFAULT_OPENCV2_NOSE_CASCADE) {

			@Override
			public void onDebugImagePrepared(Image image) {
				if (showDebug) {
					showDebug(image);
					onFacesDetected(image, getLastFoundFaces());
				}
			}
		};
		application.getAlgorithms().add(algorithm1);
	}
	
	protected void onFacesDetected(Image debugImage, List<Rectangle> locations) {
		//tcpServer.send(location.x, location.y, location.width, location.height);
	}
	
	@Override
	protected void onShowDebugChanged(boolean newValue) {
		super.onShowDebugChanged(newValue);
		this.showDebug = newValue;
	}
	
	@Override
	protected void startApp() {
		super.startApp();
		tcpServer.start();
	}
	
	@Override
	protected void stopApp() {
		super.stopApp();
		tcpServer.stop();
	}
	
	public static void main(String[] args) throws AWTException {
		int port = 9001;
		System.out.println("Starting server on port " + port);
		new FaceDetectionGUIServer(port).showFrame();
	}
}
